package com.ansion.baseui.base.loading;

import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.appcompat.app.AlertDialog;

import com.ansion.baseui.R;


public final class CustomAlertDialog extends AlertDialog {

    public static final int ONLY_TEXT = -2;
    private TextView m_textView;
    private TextView m_subTextView;
    private CharSequence m_tip;
    private View m_progress;
    private ImageView m_imageView;
    private int m_IconId;
    private CharSequence subtext;

    public CustomAlertDialog(Context context) {
        super(context, androidx.appcompat.R.style.Theme_AppCompat_DayNight_Dialog);
    }

    @Override
    public void setMessage(CharSequence message) {
        m_tip = message;
        if (null != m_textView) {
            m_textView.setText(message);
        }
    }

    public void setSubMessage(CharSequence message) {
        subtext = message;
        if (null != m_subTextView) {
            setSubText(message);
        }
    }

    public void setUpdateIcon(int resImgId) {
        m_IconId = resImgId;
        updateCustomIcon();
    }

    private void updateCustomIcon() {
        if (null == m_imageView || null == m_progress) {
            return;
        }

        if (m_IconId > 0) {
            m_imageView.setBackgroundResource(m_IconId);
            m_imageView.setVisibility(View.VISIBLE);
            m_progress.setVisibility(View.GONE);
        } else if (m_IconId == ONLY_TEXT) {
            m_imageView.setVisibility(View.GONE);
            m_progress.setVisibility(View.GONE);
        } else {
            m_imageView.setVisibility(View.GONE);
            m_progress.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Window window = getWindow();
        window.setBackgroundDrawableResource(R.color.transparent);
        WindowManager.LayoutParams attributes = window.getAttributes();
        attributes.gravity = Gravity.CENTER;
        window.setAttributes(attributes);
        setContentView(R.layout.layout_loading_dialog);
        m_textView = (TextView) findViewById(R.id.alert_text);
        m_textView.setText(m_tip);
        m_subTextView = (TextView)findViewById(R.id.alert_text_sub);
        setSubText(subtext);
        m_progress = findViewById(R.id.alert_progress);
        m_imageView = (ImageView) findViewById(R.id.alert_icon);
        updateCustomIcon();
    }

    private void setSubText(CharSequence text) {
        if (!TextUtils.isEmpty(text)) {
            m_subTextView.setVisibility(View.VISIBLE);
            m_subTextView.setText(text);
        } else {
            m_subTextView.setVisibility(View.GONE);
        }
    }
}
